<template>
  <div class="createPolicy">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <!-- <el-breadcrumb-item>
                    <i class="el-icon-s-promotion"></i> 车辆配置
                </el-breadcrumb-item> -->
        <el-breadcrumb-item> 采集策略配置</el-breadcrumb-item>
        <el-breadcrumb-item> 创建新策略</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content">
      <div class="main">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="demo-ruleForm"
          label-width="120px" status-icon style="width: 50%">
          <el-form-item label="提出部门" prop="demandDepartment">
            <el-input v-model="ruleForm.demandDepartment" />
          </el-form-item>
          <el-form-item label="开发部门" prop="developDepartment">
            <el-input v-model="ruleForm.developDepartment" />
          </el-form-item>
          <el-form-item label="策略类型" prop="scFlag">
            <!-- false 表示 trigger，  true 表示sc -->
            <el-select v-model="ruleForm.scFlag" placeholder="请选择" style="width: 100%" disabled>
              <el-option label="trigger" :value="false">
              </el-option>
              <el-option label="SC" :value="true">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="ID" prop="id">
            <el-input v-model="ruleForm.id" disabled />
          </el-form-item>
          <el-form-item label="场景" prop="sceneId">
            <el-select v-model="ruleForm.sceneId" placeholder="" style="width: 100%">
              <el-option v-for="item in sceneOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="策略名称" prop="strategyName">                                                
            <el-input v-model="ruleForm.strategyName" />
          </el-form-item>
          <el-form-item label="策略描述" prop="strategyDesc">
            <el-input v-model="ruleForm.strategyDesc" />
          </el-form-item>

          <el-form-item label="数据包内容" prop="content">
            <el-input v-model="ruleForm.content" />
          </el-form-item>


          <el-form-item prop="priority" style="width: 100%">

            <template #label>
              优先级
              <el-tooltip class="box-item" effect="light" placement="top-start">

                <template #content>
                  <div v-if="projectNameIsJ3">
                      优先级：1【紧急】<br/>
                      优先级：2【高优】<br/>
                      优先级：3【普通】
                  </div>
                  <div v-else>
                      优先级：1-3 【普通】<br/>
                      优先级：4-7 【车端 - 高优先(算法) 云端 - 高优】<br/>
                      优先级：8-10【车端/云端 - 紧急】
                  </div>
              </template>
                <i class="el-icon-warning-outline"
                  style="width: 2%;font-weight:bold;cursor: pointer;margin-right: 1%"></i>

              </el-tooltip>
            </template>

            <el-select v-model="ruleForm.priority" placeholder="" style="width: 100%">
              <el-option v-for="item in 10" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-row style="height: 40px; padding-left: 15px" class="no-margin-left">
            <el-form-item
              label="采集时长"
              style="padding-left: 5px; padding-right: 10px"
            >
              <el-col style="font-weight: lighter; width: 50px"> 触发前</el-col>
            </el-form-item>
            <el-form-item>
              <el-input-number
                v-model="ruleForm.collectTimeBefore"
                controls-position="right"
                :min="0"
                :max="15"
                label="描述文字"
                style="width: 135px"
              ></el-input-number>
            </el-form-item>
            <el-form-item style="width: 10px" />
            <el-form-item>
              <el-col style="font-weight: lighter"> ~</el-col>
            </el-form-item>
            <el-form-item style="width: 10px" />
            <el-form-item
              style="color: black; padding-left: 5px; padding-right: 10px"
            >
              <el-col style="font-weight: lighter; width: 50px"> 触发后</el-col>
            </el-form-item>
            <el-form-item>
              <el-input-number
                v-model="ruleForm.collectTimeAfter"
                controls-position="right"
                :min="0"
                :max="14"
                label="描述文字"
                style="width: 130px"
              />
            </el-form-item>
          </el-row>
          <el-form-item label="单日采集次数" prop="count">
            <el-input-number v-model="ruleForm.count"/>
          </el-form-item>

          <!--                    <el-form-item label="状态" prop="status">-->
          <!--                        <el-select v-model="ruleForm.status" placeholder="" style="width: 100%" disabled    >-->
          <!--                            <el-option-->
          <!--                                v-for="item in statusOptions"-->
          <!--                                :key="item.value"-->
          <!--                                :label="item.label"-->
          <!--                                :value="item.value"-->
          <!--                            />-->
          <!--                        </el-select>-->
          <!--                    </el-form-item>-->

          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
            <el-button type="primary" @click="returnBack">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>


<script>
import { onMounted, reactive, ref, toRaw, watch,computed } from 'vue'
import { useRoute, useRouter } from "vue-router";
import { getSceneListApi, policyEditApi } from "@/api/carManage/policyManage.js";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
export default {

  setup() {
     // J3的故障等级是1（紧急）2（高优）3（普通）,暂不修改逻辑，只更新文本描述，20240103
    // const priorityOptions = ref([
    //   {
    //     value: 2,
    //     label: '普通',
    //   }, {
    //     value: 4,
    //     label: '高优',
    //   }, {
    //     value: 10,
    //     label: '紧急',
    //   },
    // ]);
    const statusOptions = ref([
      {
        value: 0,
        label: '暂停',
      }, {
        value: 1,
        label: '启用',
      },
    ]);
    const ruleFormRef = ref();
    const ruleForm = reactive({
      demandDepartment: '',
      developDepartment: '',
      scFlag: null,
      id: '',
      sceneId: '',
      strategyName: '',
      strategyDesc: '',
      content: '',
      priority: '',
      status: '',
      modifyBy: '',
      collectTimeBefore: 8,
      collectTimeAfter: 6,
      count: 100
    })
    const rules = reactive({
      demandDepartment: [
        { required: true, message: '请输入需求部门', trigger: 'blur' },
      ],
      developDepartment: [
        { required: true, message: '请输入开发部门', trigger: 'blur' },
      ],
      scFlag: [
        { required: true, message: '请选择策略类型', trigger: 'blur' },
      ],
      id: [
        { required: true, message: '请输入ID', trigger: 'blur' },
      ],
      sceneId: [
        { required: true, message: '请选择场景', trigger: 'blur' },
      ],
      strategyName: [
        { required: true, message: '请输入策略名称', trigger: 'blur' },
      ],
      strategyDesc: [
        { required: true, message: '请输入策略描述', trigger: 'blur' },
      ],
      content: [
        { required: true, message: '请输入数据包内容', trigger: 'blur' },
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'blur' },
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'blur' },
      ],
      count: [
        { required: true, message: "请输入单日采集次数", trigger: "blur" },
      ],
    })

    const editor = ref('');
    try {
      editor.value = JSON.parse(localStorage.getItem('userInfo')).employeeId;
      ruleForm.modifyBy = editor.value;
    } catch (e) {

    }
    const sceneOptions = ref([]);
    const getSceneListFn = () => {
      getSceneListApi({}).then(res => {
        if (res.data.code == 200) {
          sceneOptions.value = res.data.data;
        }
      })
    }
    const store = useStore();
    const projectObj = computed(() => store.state.projectObj);
    // 判断项目名称是否包含J3,若包含则更新优先级的文案描述
    const projectNameIsJ3 = computed(() => {
        if(projectObj && projectObj.value.name){
            let projectName = projectObj.value.name
            return projectName.indexOf('J3') > -1
        }else {
            return false
        }    
    })
    const router = useRouter();
    const submitForm = async (formEl) => {
      let req = JSON.parse(JSON.stringify(toRaw(ruleForm)))
      let policyData = JSON.parse(sessionStorage.getItem('policyRowData'));

      Object.keys(req).forEach(item => {
        if (req[item] === policyData[item]) {
          Reflect.deleteProperty(req, item)
        }
      })
      // console.log('req',req, req.collectTimeBefore)
      // console.log('req',req)
      req.id = policyData.id;
      if (!formEl) return
      // 策略名称 、策略描述、数据包内容、优先级、 采集前、采集后 、 提出部门、开发部门、场景、单日采集次数 都未更改的话，不提交请求
      if (!req.content && !req.priority && !req.strategyDesc && !req.strategyName && req.collectTimeBefore === undefined && req.collectTimeAfter === undefined && !req.demandDepartment && !req.developDepartment && !req.sceneId && !req.count ) {
        ElMessage({
          message: '未修改任何数据，暂不提交',
          type: 'warning',
        })
        return 
      }
      await formEl.validate((valid, fields) => {
        if (valid) {
          policyEditApi(req).then(res => {
            if (res.data.data == 1) {
              ElMessage({
                message: '更新成功',
                type: 'success',
              })

              router.replace({
                path: '/triggerConfiguration/PolicyManage',
              });
            } else {
              ElMessage({
                message: '更新失败',
                type: 'error',
              })
            }
          })
        }
      })

    }
    const returnBack = () => {
      router.push({
        path: '/triggerConfiguration/PolicyManage',
      });
    }
    onMounted(() => {


    })
    const route = useRoute();
    watch(() => route.query.key, () => {
      try {
        let policyData = JSON.parse(sessionStorage.getItem('policyRowData'));
        ruleForm.demandDepartment = policyData.demandDepartment;
        ruleForm.scFlag = policyData.scFlag;
        ruleForm.id = policyData.id;
        ruleForm.strategyName = policyData.strategyName;
        ruleForm.strategyDesc = policyData.strategyDesc;
        ruleForm.content = policyData.content;
        ruleForm.priority = policyData.priority;
        ruleForm.status = policyData.status;
        ruleForm.createBy = policyData.createBy;

        ruleForm.developDepartment = policyData.developDepartment;
        ruleForm.sceneId = policyData.sceneId;
        ruleForm.collectTimeBefore = policyData.collectTimeBefore;
        ruleForm.collectTimeAfter = policyData.collectTimeAfter;
        ruleForm.count = policyData.count;

        getSceneListFn();
      } catch (e) {

      }
    }, {
      immediate: true
    })
    return {
      ruleForm,
      rules,
      ruleFormRef,
      // priorityOptions,
      statusOptions,
      submitForm,
      editor,
      sceneOptions,
      returnBack,
      projectNameIsJ3
    }
  }
}
</script>

<style lang="less" scoped>
.createPolicy {
  .crumbs {
    display: flex;
    align-items: center;
    padding: 10px;
    margin-top: 5px;
  }

  .content {
    padding: 20px;
    //background: #eeeeee;
    height: 100%;

    .main {
      padding: 20px;
      background: #FFFFFF;
      display: flex;
      justify-content: center;
    }


  }
}
</style>
<style lang="less">
    .no-margin-left{
        margin-bottom: 20px;
        .el-form-item__content{
            margin-left: 0 !important;
        }
    }
</style>